import axios from 'axios'
import { useUserStore } from "@/store/user"
import {useRouter} from 'vue-router'
import Message from '@/components/lib/Message'

// create an axios instance
const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASEURL, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
request.interceptors.request.use(
  config => {
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers['Authorization'] = userStore.profile.token
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
request.interceptors.response.use(
  response => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== '1') {
      Message({type: 'error', text: res.message})

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === '401') {
        // 清空token
        const userStore = useUserStore()
        userStore.delUserInfo().then(() => {
          location.reload()
        })

        const router = useRouter()
        
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({type: 'error', text: error.response ? error.response.data.message : '网络出错'})
    return Promise.reject(error)
  }
)

export default request
